<template>
  <router-view />
</template>

<script setup>
import { isWeChatBrowser } from '@/utils/util'
import {
  getAccessToken,
  getSystemMemberInfo,
  getMemberOpenIdInfo,
  putSystemMember,
  memberShare,
} from '@/api/api'
import axios from 'axios'
import { useRouter } from 'vue-router'
const router = useRouter()

const appid = 'wx454b020f20003032'
const appsecret = 'c69f02b12665cdfdb6ceffabd53d6bca'
const UserInfo = {
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  remark: null,
  id: null,
  memberName: null,
  memberPicture: null,
  phonenumber: null,
  cumulativeMoney: null,
  accountBalance: null,
  memberSex: null,
  memberBirthday: null,
  memberSexCh: null,
  status: 0,
  inviteBy: null,
  memberEndDate: null,
  memberLevel: null,
  memberInvite: null,
  code: null,
  startDate: null,
  endDate: null,
  openId: null,
  memberBeginDate: null,
}
onBeforeMount(async () => {
  let url = window.location.href
  const search = url.split('?')[1]
  let shareId = null
  if (search && search.includes('id')) {
    shareId = search.split('id=')[1].split('&')[0]
  }
  localStorage.setItem('shareId', shareId)
  getUser()
})

const getUser = async () => {
  let userInfo = JSON.parse(localStorage.getItem('userInfo')) || UserInfo

  // 判断是否是微信浏览器
  if (isWeChatBrowser()) {
    // 获取微信用户信息
    let url = window.location.href

    if (url.indexOf('code=') == -1) {
      let currentURL = encodeURIComponent(url)
      let redirect_uri = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${currentURL}&response_type=code&scope=snsapi_userinfo&forcePopup=true&state=STATE#wechat_redirect`
      window.location.href = redirect_uri
    } else {
      let code = url.split('code=')[1].split('&')[0]
      getAccessToken({ code: code }).then(async (res) => {
        if (res.code == 200) {
          // 通过openid获取用户信息
          getMemberOpenIdInfo(res.data.openid).then((res) => {
            if (res.code == 200) {
              let user = res.data.user || UserInfo
              localStorage.setItem('token', res.data.token)
              localStorage.setItem('userInfo', JSON.stringify(user))

              // 分享
              let shareId = localStorage.getItem('shareId')
              if (shareId) {
                memberShare({ openId: user.openId, shareId: shareId })
              }
            }
          })
        }
      })
    }
    router.push({ path: '/vip' })
  } else {
    if (userInfo.id == null) {
      router.push({ path: '/vip' })
    }
  }
}
</script>

<style lang="less">
.app-page {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.w100 {
  width: 100%;
}
</style>
